#!/usr/bin/env python3
import sys
import os
import os.path
import subprocess
import multiprocessing
import shutil

root_dir = os.path.abspath('../..')
prebuilts_gcc_dir = root_dir + '/prebuilts/gcc'
kernel_toolchain = prebuilts_gcc_dir + '/linux-x86/arm/gcc-linaro-7.5.0-arm-linux-gnueabihf/bin'

os.environ['ARCH'] = 'arm'
os.environ['CROSS_COMPILE'] = kernel_toolchain + '/arm-linux-gnueabihf-'
os.environ['PRODUCT_PATH'] = 'vendor/raspberrypi/rpi4b'

defconfig = 'rpi_4_32b_defconfig'
script_dir = os.path.abspath(os.path.dirname(__file__))
uboot_dir = os.path.join(script_dir,'u-boot-2021.07')
command = sys.argv[1]
build_dir = sys.argv[2]
output_dir = sys.argv[3]

def remove_file(name):
    try:
        os.unlink(name)
    except FileNotFoundError:
        return

def remove_directory(name):
    try:
        shutil.rmtree(name)
    except FileNotFoundError:
        pass

def copy_src_to_build_dir():
    remove_directory(build_dir)
    shutil.copytree(uboot_dir, build_dir)

def make_uboot():
    oldpwd = os.getcwd()
    copy_src_to_build_dir()
    os.chdir(build_dir)

    uboot_bin = os.path.join(output_dir, 'u-boot.bin')
    remove_file(uboot_bin)
    nproc = multiprocessing.cpu_count()
    subprocess.run(F'make {defconfig}', shell=True, check=True)
    subprocess.run(F'make -j{nproc+1}', shell=True, check=True)
    shutil.copy(
        os.path.join('u-boot.bin'),
        uboot_bin
    )

    os.chdir(oldpwd)

command_table = {
    'uboot': make_uboot,
}

command_table[command]()
